<template>
  <view 
    class="wheel-canvas-wrapper"
    :id="containerId"
    @touchstart="receiveEvent"
    @touchmove="receiveEvent"
    @touchend="receiveEvent"
    @touchcancel="receiveEvent"
  >
    <canvas 
      :id="canvasId" 
      type="2d"
      class="wheel-canvas"
    ></canvas>
    
    <!-- GO 按钮 -->
    <view class="go-button" @click="startSpin">
      <text class="go-text">GO</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
// #ifdef MP-WEIXIN
import { Leafer, Ellipse, Rect, Group } from '@leafer-ui/miniapp'
// #endif

const props = defineProps({
  /**
   * 转盘选项配置
   */
  options: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['spin-end'])

const canvasId = ref('wheel-canvas-' + Date.now())
const containerId = ref('wheel-container-' + Date.now())
const leaferInstance = ref(null)
const wheelGroup = ref(null)
const isSpinning = ref(false)
const currentRotation = ref(0)
const canvasSize = ref(300) // 默认尺寸，实际会根据设备计算

/**
 * 初始化 LeaferJS 转盘
 */
const initWheel = async () => {
  // #ifdef MP-WEIXIN
  try {
    console.log('开始初始化 LeaferJS，Canvas ID:', canvasId.value)
    
    // 获取系统信息，计算实际像素尺寸
    const systemInfo = uni.getSystemInfoSync()
    const pixelRatio = systemInfo.pixelRatio || 2
    
    // 600rpx 转换为实际像素
    const rpxToPx = systemInfo.windowWidth / 750
    const calculatedSize = Math.floor(600 * rpxToPx)
    canvasSize.value = calculatedSize
    
    console.log('Canvas 尺寸:', calculatedSize, 'px')
    
    // 创建 Leafer 实例（小程序环境暂不配置 eventer）
    leaferInstance.value = new Leafer({
      view: canvasId.value,
      width: calculatedSize,
      height: calculatedSize
    })
    
    // 创建转盘组（中心点）
    wheelGroup.value = new Group({
      x: calculatedSize / 2,
      y: calculatedSize / 2
    })
    
    // 绘制转盘扇形
    drawWheel()
    
    leaferInstance.value.add(wheelGroup.value)
    
    console.log('✅ 转盘初始化成功')
    
    // 提示用户
    uni.showToast({
      title: '转盘加载成功',
      icon: 'success',
      duration: 1500
    })
  } catch (error) {
    console.error('❌ 初始化转盘失败:', error)
    uni.showToast({
      title: '转盘加载失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
  // #endif
}

/**
 * 绘制转盘
 */
const drawWheel = () => {
  if (!wheelGroup.value || props.options.length === 0) return
  
  // 根据 Canvas 尺寸计算转盘半径（留出一些边距）
  const radius = (canvasSize.value / 2) * 0.8
  const centerX = 0
  const centerY = 0
  const anglePerOption = 360 / props.options.length
  
  console.log('绘制转盘，半径:', radius)
  
  props.options.forEach((option, index) => {
    const startAngle = index * anglePerOption - 90
    
    // 创建扇形区域
    const wedge = new Ellipse({
      width: radius * 2,
      height: radius * 2,
      innerRadius: 0,
      startAngle: startAngle,
      endAngle: startAngle + anglePerOption,
      fill: option.color,
      stroke: '#FFFFFF',
      strokeWidth: 3
    })
    
    wheelGroup.value.add(wedge)
    
    // 添加文字标签 (简化版本，实际需要计算文字位置)
    const textAngle = startAngle + anglePerOption / 2
    const textRadius = radius * 0.7
    const textX = Math.cos(textAngle * Math.PI / 180) * textRadius
    const textY = Math.sin(textAngle * Math.PI / 180) * textRadius
    
    // 这里使用矩形作为文字占位符，实际项目中需要使用 Text 元素
    const textBg = new Rect({
      x: textX - 40,
      y: textY - 15,
      width: 80,
      height: 30,
      fill: 'rgba(255, 255, 255, 0.3)',
      cornerRadius: 5
    })
    
    wheelGroup.value.add(textBg)
  })
  
  // 添加中心圆（根据半径比例调整）
  const centerCircleSize = radius * 0.25
  const centerCircle = new Ellipse({
    width: centerCircleSize,
    height: centerCircleSize,
    fill: '#FFFFFF',
    stroke: '#E0E0E0',
    strokeWidth: 2
  })
  
  wheelGroup.value.add(centerCircle)
  
  console.log('转盘绘制完成，扇形数量:', props.options.length)
}

/**
 * 开始转动
 */
const startSpin = () => {
  if (isSpinning.value || props.options.length === 0) return
  
  isSpinning.value = true
  
  // 随机选择一个结果
  const randomIndex = Math.floor(Math.random() * props.options.length)
  const anglePerOption = 360 / props.options.length
  
  // 计算目标角度：多转几圈 + 随机位置
  const spins = 5 // 转5圈
  const targetAngle = 360 * spins + randomIndex * anglePerOption + Math.random() * anglePerOption
  
  // 执行动画
  animateWheel(targetAngle, randomIndex)
}

/**
 * 转盘动画
 * @param {number} targetAngle - 目标角度
 * @param {number} resultIndex - 结果索引
 */
const animateWheel = (targetAngle, resultIndex) => {
  // #ifdef MP-WEIXIN
  if (!wheelGroup.value) return
  
  const duration = 3000 // 3秒
  const startTime = Date.now()
  const startRotation = currentRotation.value
  
  const animate = () => {
    const elapsed = Date.now() - startTime
    const progress = Math.min(elapsed / duration, 1)
    
    // 缓动函数：先快后慢
    const easeOut = 1 - Math.pow(1 - progress, 3)
    
    currentRotation.value = startRotation + targetAngle * easeOut
    wheelGroup.value.rotation = currentRotation.value
    
    if (progress < 1) {
      requestAnimationFrame(animate)
    } else {
      // 动画结束
      isSpinning.value = false
      emit('spin-end', props.options[resultIndex])
    }
  }
  
  animate()
  // #endif
}

/**
 * 接收触摸事件
 */
const receiveEvent = () => {
  // 事件接收处理
}

onMounted(() => {
  // 在小程序中需要足够的延迟时间，确保 Canvas 完全渲染
  // 直接延迟初始化，不做额外的查询验证（简化逻辑）
  setTimeout(() => {
    console.log('开始初始化转盘...')
    initWheel()
  }, 500)
})

/**
 * 暴露方法给父组件
 */
defineExpose({
  startSpin
})
</script>

<style lang="scss" scoped>
.wheel-canvas-wrapper {
  position: relative;
  width: 600rpx;
  height: 600rpx;
  
  .wheel-canvas {
    width: 100%;
    height: 100%;
  }
  
  .go-button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #FF6B9D 0%, #C06595 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 20rpx rgba(255, 107, 157, 0.4);
    cursor: pointer;
    
    &:active {
      transform: translate(-50%, -50%) scale(0.95);
    }
    
    .go-text {
      color: white;
      font-size: 40rpx;
      font-weight: bold;
    }
  }
}
</style>

